package org.brisling.docManage.queryService;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.brisling.authorize.shiro.ShiroSecurityService;
import org.brisling.base.domain.BSListDomain;
import org.brisling.base.domain.ListDomain;
import org.brisling.base.service.AbstractBaseQueryService;
import org.brisling.common.ConstSysParam;
import org.brisling.common.SysConfig;
import org.brisling.common.util.JsonUtil;
import org.brisling.common.util.LongUtil;
import org.brisling.common.util.MapUtil;
import org.brisling.common.util.StringUtil;
import org.brisling.docManage.domain.Docdetail;
import org.brisling.mobile.vo.document.VODoctype;
import org.brisling.sysman.domain.UploadFiles;
import org.brisling.sysman.queryService.QueryDictionaryService;
import org.brisling.sysman.queryService.QueryUploadService;
import org.brisling.sysman.service.UploadService;
import org.brisling.websocket.domain.WSView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * 文档明细查询服務service
 * @Author : jackson wang
 * @Date   : 2015年6月8日 下午4:18:01
 * @version: 1.0
 */
@RestController
@RequestMapping("/document/query")
public class QueryDocService extends AbstractBaseQueryService<Docdetail>{
	
	//自动匹配登录验证服务类
	@Autowired
	private ShiroSecurityService shiroSecurityService;
	
	@Autowired
	private QueryUploadService qryUploadService;
	@SuppressWarnings("unused")
	@Autowired
	private QueryDictionaryService dicService;
	@Autowired
	private UploadService uploadService;
	
	
	public QueryDocService(){
		this.subSystem = ConstSysParam.SUBSYSTEM_DOCUMENT;
		this.moduleName = ConstSysParam.MODULE_DOCDETAIL;
		this.tableName = ConstSysParam.VIEW_PREFIX+ConstSysParam.MODULE_DOCDETAIL;
		this.clazz = Docdetail.class;	
		
		
		orderMap.put("public_date","desc");
		orderMap.put("sortedid",null);			
		typeMap = this.getTypeMap(clazz);
		
	}
	
	@PersistenceContext(unitName=ConstSysParam.SUBSYSTEM_SYSMAN)
	@Autowired
	protected void setEntityManager(EntityManager entityManager){
		this.entityManager = entityManager;		
	}
	
	@RequestMapping("/mainPage.action")
	public ModelAndView getMainPage(){
		return this.getBizMainPage();
	}
	
	/* (non-Javadoc)
	 * @see org.brisling.service.sysman.DepartmentServiceInf#getEditPage()
	 */
	@RequestMapping("/editPage.action")
	public ModelAndView getEditPage(){
		return this.getBizEditPage();
	}	
	
	@RequestMapping("/auditPage.action")
	public ModelAndView getAuditPage(){
		return new ModelAndView("/"+ConstSysParam.SUBSYSTEM_DOCUMENT+"/docdetailAudit");
	}
	
	@RequestMapping("/getPage.action")
	public ModelAndView getPage(@RequestParam(value="code",required=false) String code){
		
		String _code = code==null?"main":code;
		return new ModelAndView("/"+ConstSysParam.SUBSYSTEM_DOCUMENT+"/"+_code);
	}	
	
	/* (non-Javadoc)
	 * @see org.brisling.service.sysman.DepartmentServiceInf#getEditPage()
	 */
	@RequestMapping("/moduleEditPage.action")
	public ModelAndView getModuleEditPage(@RequestParam(value="module",required=false) String module){
		if(module!=null && module.trim().length()>0){
			return new ModelAndView("/"+ConstSysParam.SUBSYSTEM_DOCUMENT+"/"+module+"Dlg");
		}else{
			
			return new ModelAndView("/"+ConstSysParam.SUBSYSTEM_DOCUMENT+"/docdetailDlg");
		}
	}	
	
	@RequestMapping("/moduleListPage.action")
	public ModelAndView getModuleListPage(@RequestParam(value="module",required=false) String module){
		if(module!=null && module.trim().length()>0){
			return new ModelAndView("/"+ConstSysParam.SUBSYSTEM_DOCUMENT+"/"+module+"List");
		}else{
			return new ModelAndView("/"+ConstSysParam.SUBSYSTEM_DOCUMENT+"/docdetailList");
		}
	}	
	
	@RequestMapping("/getListDomain.action")
	public ListDomain<Docdetail> getListDomain(@RequestBody(required=false) String body){		
		
		
		return super.getListDomainByConditionAndOrder(null,body, Docdetail.class, orderMap,true);
	}
	
	/**
	 * 获取指定条件的列表数据
	 * @param body
	 * @return
	 */
	@RequestMapping("/getList.action")
	public List<Docdetail> getList(@RequestBody(required=false) String body){		
		
		
		@SuppressWarnings("unchecked")
		Map<String,Object> map = JsonUtil.body2Class(body, Map.class);
		
		//执行查询		
		return this.getList(map);		
	}
	
	/**
	 * 获取指定条件的列表数据
	 * @param body
	 * @return
	 */
	
	public List<Docdetail> getList(Map<String,Object> map){		
		
		//定义sql
		String sql = "select * from " + this.tableName 
				+ " where 1=1 "
				+ "<#if typeid ??>and typeId=${typeid}</#if> "
				+ "order by public_date desc ";
		
				
		//格式化sql
		sql = StringUtil.formatSql(sql, map);
		
		//获取分页参数
		String sp = MapUtil.getMapData(map, "page");
		String sr = MapUtil.getMapData(map, "rows");
		
		Integer page = LongUtil.getIntValue(sp, 0);
		Integer pageSize = LongUtil.getIntValue(sr, 5);
		
		//执行查询		
		return super.getPagedList(page, pageSize, sql);
		
	}
	
	/**
	 * bootstrap grid 实体结果查询封装方法
	 * @param body
	 * @return
	 */
	@RequestMapping("/getBSListDomain.action")
	public BSListDomain<Docdetail> getBSListDomain(@RequestBody(required=false) String body){		
		
		BSListDomain<Docdetail> bsdomain = new BSListDomain<Docdetail>();
		ListDomain<Docdetail> domain = getListDomain(body);
		if(domain.getTotal()!=null){
			bsdomain.setPage_data(domain.getRows());
			bsdomain.setTotal_rows(domain.getTotal());
		}
		
		return bsdomain;
		
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping("/getAuditListDomain.action")
	public ListDomain<Docdetail> getAuditListDomain(@RequestBody(required=false) String body){		
		Map<String,Object> map = this.getBodyParam(body);
		Map<String,String> param_map = (Map<String, String>) map.get(ConstSysParam.CONDITION_MAP_KEY);
		param_map.put("status_le", "0");
		map.put(ConstSysParam.CONDITION_MAP_KEY, param_map);
		return super.getListDomainByConditionAndOrder(null,map, typeMap, orderMap,true);
	}
	
	@RequestMapping("/getPicListDomain.action")
	public List<UploadFiles> getPicListDomain(@RequestBody(required=false) String body){		
		
		//获取文档清单
		ListDomain<Docdetail> details = super.getListDomainByConditionAndOrder(null,body, Docdetail.class, orderMap,true);
		
		String ids = null;
		String typeCode = null;
		if(details!=null && details.getRows().size()>0){
			typeCode = details.getRows().get(0).getTypeCode();
			Integer _count = details.getRows().size();
			for(int i=0;i<_count;i++){
				Docdetail doc = details.getRows().get(i);
				
				String notNullTemplate = "%1$s,'%2$d'";
				if(doc!=null && doc.getId()!=null){
					String curDocid = "'" + doc.getId() +"'";
					ids=ids==null?curDocid:String.format(notNullTemplate,ids ,doc.getId());
				}
			}
		}
		
		if((ids!=null) && (typeCode!=null)){
			Map<String,String> map = new HashMap<String,String>();
			map.put("bizcode", typeCode);
			map.put("bizno_in", ids);			
			return qryUploadService.getList(map);
		}
		List<UploadFiles> lists = new ArrayList<UploadFiles>();
		return lists;
	}
	
	
	/**
	 * easyui datagrid domain
	 * @param body
	 * @return
	 */
	@RequestMapping("/getTypeListDomain.action")
	public ListDomain<Docdetail> getTypeListDomain(@RequestBody(required=false) String body){
		ListDomain<Docdetail> domains = super.getListDomainByConditionAndOrder(null, body, clazz, orderMap, false);
		if(domains.getRows()!=null && domains.getRows().size()>0){
			List<Docdetail> lists = domains.getRows();
			if(lists!=null && lists.size()>0){
				for(int i=0;i<lists.size();i++){
					String _s = lists.get(i).getForm_content();
					if(_s!=null){
						_s = StringUtils.normalizeSpace(_s);
					}							
					lists.get(i).setForm_content(_s);
				}
			}
			domains.setRows(lists);
		}
		return 		domains;
	}
	
	/**
	 * bootstrap bs_grid domain
	 * @param body
	 * @return
	 */
	@RequestMapping("/getTypeBSListDomain.action")
	public BSListDomain<Docdetail> getTypeBSListDomain(@RequestBody(required=false) String body){		
		BSListDomain<Docdetail> bsdomain = new BSListDomain<Docdetail>();
		ListDomain<Docdetail> domain = getTypeListDomain(body);	
		if(domain.getTotal()!=null){
			bsdomain.setTotal_rows(domain.getTotal());
			bsdomain.setPage_data(domain.getRows());			
		}
		return bsdomain;
	}
	
	@RequestMapping("/getTypeListDomainConcat.action")
	public ListDomain<Docdetail> getTypeListDomainConcat(@RequestBody(required=false) String body){		
		ListDomain<Docdetail> domains =  this.getTypeListDomain(body);			
		if(domains!=null && domains.getTotal()>0){
			Map<String,Object> map = this.getBodyParam(body);
			
			Integer titleCharMax = 15;
			
			Integer titleCharMid = 10;
			
			Integer titleCharMin = 8;
			
			Integer window_width_divide_max = 1440;
			
			Integer window_width_divide_mid = 1024;
			
			Integer _windowWidth = 1024;
			//获取屏幕宽度
			if(map.containsKey("windowWidth")){
				Object obj = map.get("windowWidth");
				if(obj!=null){
					_windowWidth = LongUtil.getIntValue(obj.toString(), null);					
				}
			}
			
			//获取屏幕宽度划分标准
			Object obj = SysConfig.getConfig("window_width_divide_max");			
			if(obj!=null){
				window_width_divide_max = LongUtil.getIntValue(obj.toString(), null);					
			}
			
			
			//获取屏幕宽度划分标准
			obj = SysConfig.getConfig("window_width_divide_mid");			
			if(obj!=null){
				window_width_divide_mid = LongUtil.getIntValue(obj.toString(), null);					
			}
			
			
			//获取大屏字符数
			obj = SysConfig.getConfig("titleCharMax");			
			if(obj!=null){
				titleCharMax = LongUtil.getIntValue(obj.toString(), null);					
			}
			
			//获取小屏字符数
			obj = SysConfig.getConfig("titleCharMid");			
			if(obj!=null){
				titleCharMid = LongUtil.getIntValue(obj.toString(), null);					
			}
			
			//获取小屏字符数
			obj = SysConfig.getConfig("titleCharMin");			
			if(obj!=null){
				titleCharMin = LongUtil.getIntValue(obj.toString(), null);					
			}
			
			
			
			Integer titleCharNum = _windowWidth<window_width_divide_mid?titleCharMin:
				(_windowWidth<window_width_divide_max?titleCharMid:titleCharMax);
			
			
			for(Docdetail detail:domains.getRows()){
				detail.setShortname(setStrLength(detail.getName(),titleCharNum));
			}
			
		}
		return domains;
	}
	
	
	
	private String setStrLength(String s ,int str_length){
		if(s==null || s.trim().length()<=0){
			return null;
		}
		String retVal = null;
		double valueLength = 0;
		String chinese = "[\u4e00-\u9fa5]";
		if(s.length()<=str_length){
			return s;
		}
		for(int i=0;i<s.length();i++){
			String temp = s.substring(i , i+1);
			if(temp.matches(chinese)){
				valueLength+=1;
			}else{
				valueLength+=0.5;
			}
			retVal = s.substring(0,i);
			if(Math.ceil(valueLength)>=str_length){
				retVal += "...";
				break;
			}
		}
		return retVal;
		
	}
	
	@RequestMapping("/getTreeListDomain.action")
	public ListDomain<Docdetail> getTreeListDomain(@RequestParam(value="id",required=false) Long id){
		
		return this.getPagedTreeListDomain(id);
		
	}	
	
	
	@RequestMapping("/getListByPage.action")
	public List<Docdetail> getListByPage(@RequestBody(required=false) String body){		
		
		return super.getListByConditionAndOrder(body, typeMap, orderMap, true);		
		
	}	
	
	/**
	 * 获取最新通知信息
	 * @param body
	 * @return
	 */
	@RequestMapping("/getNew.action")
	public List<Docdetail> getNew(@RequestParam(value="typeid",required=false) Integer typeid,
			@RequestParam(value="userid",required=false) String userid){
		
		
		
		Calendar c = Calendar.getInstance();
		//一周前
		c.add(Calendar.DATE, -7);
		
		String	public_date = c.get(Calendar.YEAR) + "-"+
				(c.get(Calendar.MONTH)+1) + "-" +
				c.get(Calendar.DATE);
		
		
		String _userid = userid==null?shiroSecurityService.getCurrentUserIdentify():userid;
		
		Integer _typeid = typeid==null?16:typeid;
		
		
		//一周内最新通知公告
		String sql = dicService.getSqlByBizcode("qry_doc_notification");
		sql = String.format(sql, _userid,public_date,_typeid);
		return super.getAllList(sql);
	}
	
	
	@RequestMapping("/getTreeList.action")
	public List<Docdetail> getTreeList(@RequestParam(value="id",required=false) Long id){
		
		return this.getPagedTreeList(id);
		
	}	
	
	@RequestMapping("/getOne.action")
	public Docdetail getOne(@RequestParam(value="id",required=false) Long id){
		return super.getOne(id);
	}
	
	@RequestMapping("/getListByField.action")
	public List<Docdetail> getListByField(@RequestParam(value="field",required=false)String field,
			@RequestParam(value="fieldVal",required=false)String fieldVal,@RequestBody(required=false) String body){
		
		
		if(field==null || fieldVal==null){
			Map<String,Object> map = this.getBodyParam(body);
			if(map!=null){
				if(map.containsKey("field")){
					Object obj = map.get("field");
					if(obj!=null)
						field = obj.toString();
				}
				
				if(map.containsKey("fieldVal")){
					Object obj = map.get("fieldVal");
					if(obj!=null)
						fieldVal = obj.toString();
				}
			}
		}
		return this.getListInIdentify(field, fieldVal);
		
	}
	
	@RequestMapping("/getImage.action")
	public void downloadImage(@RequestParam(value="id",required=false)Long id,HttpServletRequest request,HttpServletResponse respones){
		
		 uploadService.getImage(id, request, respones);
	}
	
	/**
	 * 获取移动端数据
	 * @param body
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/mobile.m")
	public WSView<Docdetail> getMobile(@RequestBody(required=false) String body){
		
		Map<String,Object> map = JsonUtil.body2Class(body, Map.class);
		return exec(map);
	}	
	
	/**
	 * 移动端调用入口
	 * @param map
	 * @return
	 */
	public WSView<Docdetail> exec(Map<String,Object> map) {
		// TODO Auto-generated method stub
		
		WSView<Docdetail> ret = null;
		
		if(map!=null){
			String module = MapUtil.getMapData(map, "module");			
			
			String method = MapUtil.getMapData(map, "method");
			if( (module!=null) && (method!=null) ){
				
				switch(method){
					
					case "getDetailList":
						ret = new WSView<Docdetail>(module,method);
						ret.setRows(this.getList(map));
				}
				
			}
		}
		return ret;
	}

}
